package com.example.activiti.common.exclusion;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Administrator
 */
@Slf4j
@Component
public class UserDetailsServiceImpl implements UserDetailsService {

    /**
     * 保存角色信息防止通过username覆盖之前的权限数据
     */
    private Map<String, User> userMap = new HashMap<>();

    @Override
    public UserDetails loadUserByUsername(String userNameAndRole) throws UsernameNotFoundException {
        return findOneUserByName(userNameAndRole);
    }

    private User findOneUserByName(String userNameAndRole) {
        String[] nameAndRole = userNameAndRole.split(",");
        String username = nameAndRole[0];
        if (userMap.containsKey(username)) {
            return userMap.get(username);
        }
        // 根据参数添加角色权限
        List<GrantedAuthority> authorities;
        int length = nameAndRole.length;
        int lengthHasRole = 2;
        if (length == lengthHasRole) {
            String role = nameAndRole[1];
            authorities = Arrays.asList(
                    new SimpleGrantedAuthority("ROLE_ACTIVITI_USER"),
                    new SimpleGrantedAuthority("GROUP_activitiTeam"),
                    new SimpleGrantedAuthority("ROLE_" + role),
                    new SimpleGrantedAuthority("GROUP_" + role)
            );
        } else {
            authorities = Arrays.asList(
                    new SimpleGrantedAuthority("ROLE_ACTIVITI_USER"),
                    new SimpleGrantedAuthority("GROUP_activitiTeam")
            );
        }
        User user = new User(username, "", authorities);
        userMap.put(username, user);
        return user;
    }
}
